<script setup>
import { ref, onMounted, watch } from 'vue'

const name = ref("ToDo List")

const task_content = ref([])

const todos = ref([])

function add(event) {
    if (task_content.value.trim().length === 0) {
        alert("请输入任务内容")
        return
    }
    todos.value.push({
        "id": Date.now(),
        "content": task_content.value,
        "completed": false,
    })
    task_content.value = ""  // 添加这行清空输入框
}

function deleteToDo(id) {
    todos.value = todos.value.filter(todo => todo.id !== id)
}

onMounted(() => {
    todos.value = JSON.parse(localStorage.getItem("todos")) || [];
})

watch(() => todos.value, (newValue, oldValue) => {
    localStorage.setItem("todos", JSON.stringify(newValue))
}, { deep: true })

</script>

<style scoped>
.line-through {
    text-decoration: line-through;
    color: #888;
}

.input-group {
    display: flex;
    gap: 10px;
}
</style>

<template>
    <main class="todo-container">
        <div>
            <h1>{{ name }}</h1>
        </div>

        <div class="input-group">
            <el-input type="text" v-model="task_content"></el-input>
            <el-button @click="add">新增任务</el-button>
        </div>

        <div class="todo-list">
            <ol>
                <li v-for="(todo) in todos">
                    <div>
                        <el-checkbox v-model="todo.completed"></el-checkbox>
                        <span v-bind:class="{ 'line-through': todo.completed }">
                            {{ todo.content }}
                        </span>
                        <el-button @click="deleteToDo(todo.id)">删除</el-button>
                    </div>
                </li>
            </ol>
        </div>
    </main>
</template>